using System;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class ObserveDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    private Action _onValueChange;

    public void TrySetAction(Action onValueChange)
    {
        if (_onValueChange == null)
            _onValueChange = onValueChange;
    }

    public ObserveDictionary()
    {

    }

    public new void Add(TKey key, TValue value)
    {
        base.Add(key, value);
        _onValueChange?.Invoke();
    }

    public new void Clear()
    {
        base.Clear();
        _onValueChange?.Invoke();
    }

    public new bool Remove(TKey key)
    {
        bool suc = base.Remove(key);
        if (suc)
            _onValueChange?.Invoke();
        return suc;
    }

    public new TValue this[TKey key]
    {
        get
        {
            return base[key];
        }
        set
        {
            Debug.Assert(value != null);
            if (!base.ContainsKey(key) || !value.Equals(base[key]))
            {
                base[key] = value;
                _onValueChange?.Invoke();
            }
        }
    }
}
